package com.dlj.shirospringboot.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author lijiedong
 * @version 1.0
 * @date 2020/12/3 15:11
 */
@Controller
public class IndexController {
    @RequestMapping("/index1")
    public String index(){
        System.out.println("kk");
        return "index";
    }
    @RequestMapping("/user/add")
    public String toAdd(){
        return "add";
    }
    @RequestMapping("/user/update")
    public String toUpdate(){
        return "update";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }
    @RequestMapping("/login")
    public String login(@RequestParam("username") String userName, @RequestParam("password")  String password, Model model){
        // 获取当前用户
        Subject subject = SecurityUtils.getSubject();
        // 创建token
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        // 执行登录方法，如果没有异常就说明登录了
        try {
            System.out.println("登录");
            subject.login(token);
            return "index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg","用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码不存在");
            return "login";
        }
    }
    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){

        return "未经授权，无法访问此页面";
    }
    /*@RequestMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/";
    }*/

}
